#include "uploadpicthread.h"
#include "commonfuc.h"
#include "logfile.h"
#include "clienthttp.h"
#include <QThread>
#include <QTextCodec>
#include <QFile>


uploadPicThread::uploadPicThread()
{
    QTextCodec::codecForName("utf-8");//GBK
    m_curFilePath = QString();
    m_fileName = QString();
    m_nId = 0xFFFFFFFF;
}

uploadPicThread::~uploadPicThread()
{
}

void uploadPicThread::onInitPara(quint64 id,TRANSFER_INFO info)
{
#ifdef WIN32
    int nThreadId = (int)QThread::currentThreadId();
#endif
    paraInfo = info;
    m_nId = id;
}

void uploadPicThread::onDealwithuploadPicRequest(quint64 id,QString filePath, QByteArray pic)
{
#ifdef WIN32
    int nThreadId = (int)QThread::currentThreadId();
#endif
    /*if(id != m_nId)
    {
        return;
    }*/

    QString strLog;
    if(filePath.isEmpty() || filePath.isNull())
    {
        strLog = QString("para is NULL!");
        logFile::printLog(strLog);
        return;
    }

    m_curFilePath = filePath;

    //QChar c
    int nLast = filePath.lastIndexOf('/');
    int nCount = filePath.length() - nLast - 1;
    m_fileName = filePath.right(nCount);

    //QString strUrl = QString("http://192.168.7.2:8000/dump");
    //QString strUrl = QString("http://192.168.5.136:48069/upload");

    QString strUrl = "";
    strUrl.append(paraInfo.picUrl);

    HttpClient* pHttpFun = new HttpClient();
    connect(pHttpFun,SIGNAL(signal_requestFinished(int,bool,const QString&,int)),
            this,SLOT(slot_requestFinished(int,bool,const QString&,int)));

    static int nnT = 0;
    m_nId = nnT;
    pHttpFun->sendRequest_Post(strUrl,pic,nnT);
    strLog.sprintf("--------upload pic start:%s.",m_fileName.toStdString().c_str());
    logFile::printLog(strLog);
    nnT++;
}

void uploadPicThread::slot_requestFinished(int nType,bool bSuccess, const QString& strResult,int userData)
{
#ifdef WIN32
    int nThreadId = (int)QThread::currentThreadId();
#endif
    if(userData != m_nId)
    {
        return;
    }

    QString strType;
    QString strIsSuccess;
    if(1==nType)
    {
        strType = QString("Get Rsp:");
    }
    else
    {
         strType = QString("Post Rsp:");
    }

    if(bSuccess)
    {
        strIsSuccess = QString(" success ");
        QFile::remove(m_curFilePath);
    }
    else
    {
        strIsSuccess = QString(" failure ");
    }


    QString strLog = QString("--------%1%2%3 (%4)").arg(strType,strIsSuccess,strResult,m_fileName);
    logFile::printLog(strLog);

    //emit sigPicWorkFinish(m_nId);
}
